<?php
/**
 * Author: Jesse
 * Email : jessedev@163.com
 * Date: 2024/6/18 15:16
 * FileName: ValidationExceptionHandler.php
 * DESC: The Relentless Pursuit of Perfection.
 */

namespace Common\Kernel\Exception\Handler;

use Common\Constants\ErrorCode;
use Common\Kernel\Exception\BusinessException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\MessageInterface;
use Throwable;


/**
 * 业务错误处理器
 */
class BusinessExceptionHandler extends ExceptionHandler
{
    #[Inject]
    protected ResponseInterface $response;

    /**
     * 处理验证器异常逻辑
     *
     * @param Throwable $throwable
     * @param \Psr\Http\Message\ResponseInterface $response
     * @return MessageInterface|ResponseInterface
     */
    public function handle(Throwable $throwable, \Psr\Http\Message\ResponseInterface $response): MessageInterface|ResponseInterface
    {
        // 阻止冒泡
        $this->stopPropagation();

        // 错误响应
        return $this->response->withStatus(ErrorCode::SERVER_SUCCESS)->errorJson($throwable->getCode(), $throwable->getMessage());
    }

    /**
     * 启用处理器
     *
     * @param Throwable $throwable
     * @return bool
     */
    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof BusinessException;
    }
}